package com.lljin.study.userserviceprovider.controller;

import com.lljin.study.client.OrderServiceFeignClient;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author lljin
 * @description hystrix test
 * @date 2020/7/19 23:50
 */
@DefaultProperties(defaultFallback = "defaultFallback")
@RestController
public class HystrixController {

    private final RestTemplate restTemplate;

    public HystrixController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @HystrixCommand(fallbackMethod = "fallback", commandProperties = {
            //判断是否进行熔断的最少请求数量,低于该数量将不判断是否触发熔断
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
            //熔断时间,触发熔断后*秒内会进入fallback,默认5秒
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "6000"),
            //触发降级的请求失败百分比,默认50%
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),
            //是否开启熔断,默认为true
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true")
    })
    @GetMapping("/hystrix/circuitBreakerTest/{num}")
    public String hystrixTest(@PathVariable int num) {
        if (num == 1) {
            return "服务正常返回";
        }
        //服务错误导致熔断降级
        return restTemplate.getForObject("http://localhost:5000/order", String.class);
    }

    @HystrixCommand(fallbackMethod = "fallback", commandProperties = {
            //是否开启超时降级
            @HystrixProperty(name = "execution.timeout.enabled", value = "true"),
            //超时时间,默认1秒
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
    })
    @GetMapping("/hystrix/timeout/{num}")
    public String timeout(@PathVariable int num) {
        //此处每次请求如果num为2的倍数,会被休眠3秒,此处配置的超时时间是2秒会导致熔断然后调用降级服务,为一次性的,下次还是会去调用服务
        //并且不会因为熔断就影响其他的请求
        return restTemplate.getForObject("http://localhost:8082/testHystrix/{num}", String.class, num);
    }
    private String fallback(int num) {
        return "触发服务降级";
    }

    private String defaultFallback() {
        return "默认降级方法";
    }
}
